import 'package:http/http.dart' as http;
import 'package:news_app_api/models/article.dart';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:news_app_api/secret.dart';

class News {
  List<Article> news = [];

  Future<void> getNews() async {
    debugPrint('开始获取头条新闻数据');
    String url =
        "https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&sortBy=publishedAt&language=en&apiKey=${apiKey}";

    debugPrint('正在发起API请求: $url');
    var response = await http.get(Uri.parse(url));
    debugPrint('收到API响应，状态码: ${response.statusCode}');

    var jsonData = jsonDecode(response.body);
    debugPrint('JSON数据解析完成');

    if (jsonData['status'] == "ok") {
      debugPrint('API状态正常，开始处理文章数据');
      int processedCount = 0;
      int addedCount = 0;

      try {
        jsonData["articles"]?.forEach((element) {
          processedCount++;
          try {
            if (element == null) {
              debugPrint('警告：遇到空的文章数据');
              return;
            }
            debugPrint('正在处理文章: ${element['title'] ?? '无标题'}');
            Article article = Article(
              title: element['title'],
              author: element['author'],
              description: element['description'],
              urlToImage: element['urlToImage'],
              publishedAt: element['publishedAt'],
              content: element["content"],
              articleUrl: element["url"],
            );
            news.add(article);
            addedCount++;
            debugPrint('文章处理成功：${article.toString()}');
          } catch (e) {
            debugPrint('处理文章时发生错误: ${e.toString()}');
          }
        });
      } catch (e) {
        debugPrint('处理新闻列表时发生错误: ${e.toString()}');
      }
      debugPrint('文章处理完成：共处理 $processedCount 篇文章，成功添加 $addedCount 篇');
    } else {
      debugPrint('API返回错误状态：${jsonData['status']}');
    }
  }
}

class NewsForCategorie {
  List<Article> news = [];

  Future<void> getNewsForCategory(String category) async {
    debugPrint('开始获取分类新闻数据，分类: $category');
    String url =
        "https://newsapi.org/v2/top-headlines?country=us&category=$category&apiKey=${apiKey}";

    debugPrint('正在发起分类新闻API请求: $url');
    var response = await http.get(Uri.parse(url));
    debugPrint('收到分类新闻API响应，状态码: ${response.statusCode}');

    var jsonData = jsonDecode(response.body);
    debugPrint('分类新闻JSON数据解析完成');

    if (jsonData['status'] == "ok") {
      debugPrint('分类新闻API状态正常，开始处理文章数据');
      int processedCount = 0;
      int addedCount = 0;

      try {
        jsonData["articles"]?.forEach((element) {
          processedCount++;
          try {
            if (element == null) {
              debugPrint('警告：遇到空的文章数据');
              return;
            }
            debugPrint('正在处理文章: ${element['title'] ?? '无标题'}');
            Article article = Article(
              title: element['title'],
              author: element['author'],
              description: element['description'],
              urlToImage: element['urlToImage'],
              publishedAt: element['publishedAt'],
              content: element["content"],
              articleUrl: element["url"],
            );
            news.add(article);
            addedCount++;
            debugPrint('文章处理成功：${article.toString()}');
          } catch (e) {
            debugPrint('处理文章时发生错误: ${e.toString()}');
          }
        });
      } catch (e) {
        debugPrint('处理分类新闻列表时发生错误: ${e.toString()}');
      }
      debugPrint('分类新闻处理完成：共处理 $processedCount 篇文章，成功添加 $addedCount 篇');
    } else {
      debugPrint('分类新闻API返回错误状态：${jsonData['status']}');
    }
  }
}
